
import { RouteType } from "@/types/router"
import routerStore from "@/stores/routerStore"
import { Router, RouteRecordRaw } from "vue-router"

const getFeilsPathObj = ()=> import.meta.glob('../views/**/*.tsx')
const modules = getFeilsPathObj()

// 创建路由
function getAllRouter(allRoute: RouteRecordRaw[], routeTree: RouteType, path?: string, p?: any): RouteRecordRaw[]
function getAllRouter(allRoute: RouteRecordRaw[], routeTree: RouteType, path = '/', p: any) {
  routeTree.children?.forEach((route) => {
    
    allRoute.push({
      path: path + (route.code as string),
      name: route.code,
      meta: {
        title: route.title,
        pName: p ? p.pName : route.code,
        pTitle: p ? p.pTitle : route.title
      },
      component: modules[`../views${path}${String(route.code)}/index.tsx`]
    }) 
    
    route?.children?.forEach((rr) => { 
      getAllRouter(allRoute, rr, "/" + (route.code as string) + "/" + (rr.code as string) + '/', { pName: route.code, pTitle: route.title }) 
    })
  })
  return allRoute
}

export default function (router: Router, test: RouteType) {
  const allRoute: Array<RouteRecordRaw> = getAllRouter([], test)
  router.addRoute({
    path: '/',
    name: "app",
    redirect: allRoute[0],
    component: () => import('../components/Menu/Menu'),
    children: allRoute
  })
  router.addRoute({
    path: '/404',
    name: "notFound",
    component: () => import('../components/NotFoundPage/index'),
  })
  router.addRoute({
    path: '/:pathMatch(.*)',
    redirect:"/404",
  })

  const store = routerStore()
  store.$patch({
    appRoute: test
  })

  router.replace({ path: '/login' })
  store.initRoute()
}